import {
  config
} from "config.js"
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

function getDateDiff(dateTime) {
  const transEnd = dateTime.replace(/-/g, '/') // 将时间格式转化为'/'
  console.log(transEnd)
  const dateTimeStamp = new Date(transEnd).getTime() // iOS系统、安卓都能正常转化了
  let result = '';
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let halfamonth = day * 15;
  let month = day * 30;
  let year = day * 365;
  let now = new Date().getTime();
  let diffValue = dateTimeStamp - now;
  if (diffValue < 0) {
    return;
  }
  let monthEnd = diffValue / month;
  let weekEnd = diffValue / (7 * day);
  let dayEnd = diffValue / day;
  let hourEnd = diffValue / hour;
  let minEnd = diffValue / minute;
  let yearEnd = diffValue / year;
  console.log(monthEnd, dayEnd, hourEnd, minEnd)
  // if (yearEnd >= 1) {
  //   result ="" + parseInt(yearEnd) + "年";
  // } else if (monthEnd >= 1) {
  //   result = "" + parseInt(monthEnd) + "月";
  // } else if (weekEnd >= 1) {
  //   result = "" + parseInt(weekEnd) + "周";
  // } else 
  if (dayEnd >= 1) {
    result = "" + parseInt(dayEnd) + "天" + parseInt(hourEnd) % 24 + "小时";
  } else if (hourEnd >= 1) {
    result = "" + parseInt(hourEnd) + "小时";
  } else if (minEnd >= 1) {
    result = "" + parseInt(minEnd) + "分钟";
  } else {
    result = "不足1分钟";
  }
  return result;
};

/***
 * 上边的哪个消息发送，封装的不是很好，
 * 这个是promise风格的，调用完之后，直接.then写逻辑
 */
const requestForPromise = (url, data, method) => {
  console.log("发起网络请求，路径=", url)
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.baseUrl + url,
      data: data,
      method: method,
      success: function (res) {
        console.log("请求结果:", res.data)
        resolve(res.data)
      },
      fail: function (res) {
        reject(res)
      }
    })
  })

}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime,
  getDateDiff,
  requestForPromise
}